package com.gridmobi.xrtb;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 分解国家城市对照表 到单独文件 ，这样减少文件大小 支持前端下拉框选择
 * 国家城市对照 参照谷歌city列表
 */
public class CountryCityFileUtil {
    static Map<String, BufferedWriter> io = Maps.newHashMap();
    static Map<String, AtomicInteger> ioCount = Maps.newHashMap();

    public static void main(String[] args) throws Exception {
        Path fpath = Paths.get("/Users/huangyongchao/dsp-admin/static/citys/city");
        String root = "/Users/huangyongchao/dsp-admin/static/citys/";

        //创建BufferedReader
        try {
            BufferedReader bfr = Files.newBufferedReader(fpath);
            final AtomicInteger i = new AtomicInteger(0);
            bfr.lines().forEachOrdered(line -> {
                JSONObject j = JSONObject.parseObject(line.substring(0, line.length() - 1));
                String label = j.getString("label");
                String key = j.getString("key");
                Integer index = j.getInteger("index");
                String country = label.substring(0, 3);
                String realPath = root.concat(country);
                Path sub = Paths.get(realPath);

                if (!Files.exists(sub)) {
                    try {
                        Files.createFile(sub);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        BufferedWriter bfw = null;
                        if (io.containsKey(country)) {
                            bfw = io.get(country);
                        } else {
                            bfw = Files.newBufferedWriter(sub);
                            io.put(country, bfw);
                        }

                        if (ioCount.containsKey(country)) {
                            ioCount.get(country).incrementAndGet();

                        } else {
                            ioCount.put(country, new AtomicInteger(1));

                        }
                        if (ioCount.get(country).get() == 1) {
                            bfw.write("[");
                        }
                        bfw.write(line);
                        bfw.flush();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                i.incrementAndGet();
            });
            io.forEach((co,bfw)->{
            });
            System.out.println(i.get());
            bfr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
